package com.lie.prepare.merge;

import org.junit.Test;

import static com.lie.prepare.util.Print.*;
/**
 * Created by lie on 2018/4/20.
 * 本例依然是2个有序链表的合并
 * 只不过我自定义了
 * @see Node 的方式来实现
 *
 * 当然这里做得可以更简洁点
 * @see ResultNodeMerge 这是网上的做法
 */
public class NodeMerge {

    public void doMerge(){
        Node link1 = Node.getLink1();
        print("有序链表1号= " +link1);
        Node link2 = Node.getLink2();
        print("有序链表2号= " +link2);

        Node mergeNode = new Node();
        mergeNode.value = -1;//初始

        compareAndMerge(mergeNode, link1, link2);

//        print("被用过的有序链表1号= " +lastOfLink1);
//        print("被用过的有序链表2号= " +lastOfLink2);

        if (lastOfLink1 != null) {
            lastOfMerge.nextNode = lastOfLink1;
        }
        if (lastOfLink2 != null) {
            lastOfMerge.nextNode = lastOfLink2;
        }

        mergeNode = mergeNode.nextNode;
        print("merge = " + mergeNode);
    }

    private Node lastOfMerge;
    private Node lastOfLink1;
    private Node lastOfLink2;

    private void compareAndMerge(Node merge, Node link1, Node link2){
        if (link1 != null && link2 != null) {
            Node tempNode = new Node();
//            print("拼接中--l1 = "+ link1);
//            print("拼接中--l2 = ***"+ link2);
            if (link1.value < link2.value) {
                tempNode.value = link1.value;
                link1 = link1.nextNode;
            }else {
                tempNode.value = link2.value;
                link2 = link2.nextNode;
            }
            merge.nextNode = tempNode;
            lastOfMerge = merge.nextNode;
            lastOfLink1 = link1;
            lastOfLink2 = link2;
            compareAndMerge(merge.nextNode, link1, link2);
        }
    }

    @Test
    public void test(){
        doMerge();
    }
}
